<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Node.js,Pomelo,Unity3D," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="系统版本：macOS 10.12.3，Pomelo版本：1.2.3，Unity版本：5.4.4f1
Pomelo Demo 服务端代码：https://github.com/vitahlin/VitahPomeloServer
Pomelo Demo 客户端代码：https://github.com/vitahlin/VitahPomeloClient
除了基本的信息交互，我们在游戏中也会时常遇到">
<meta property="og:type" content="article">
<meta property="og:title" content="Pomelo教程(10)-建筑升级倒计时的处理">
<meta property="og:url" content="http://www.vitah.net/posts/bc618efe/index.html">
<meta property="og:site_name" content="Vitah's Blog">
<meta property="og:description" content="系统版本：macOS 10.12.3，Pomelo版本：1.2.3，Unity版本：5.4.4f1
Pomelo Demo 服务端代码：https://github.com/vitahlin/VitahPomeloServer
Pomelo Demo 客户端代码：https://github.com/vitahlin/VitahPomeloClient
除了基本的信息交互，我们在游戏中也会时常遇到">
<meta property="og:updated_time" content="2017-04-10T03:40:33.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Pomelo教程(10)-建筑升级倒计时的处理">
<meta name="twitter:description" content="系统版本：macOS 10.12.3，Pomelo版本：1.2.3，Unity版本：5.4.4f1
Pomelo Demo 服务端代码：https://github.com/vitahlin/VitahPomeloServer
Pomelo Demo 客户端代码：https://github.com/vitahlin/VitahPomeloClient
除了基本的信息交互，我们在游戏中也会时常遇到">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.vitah.net/posts/bc618efe/"/>





  <title> Pomelo教程(10)-建筑升级倒计时的处理 | Vitah's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Vitah's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.vitah.net/posts/bc618efe/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Vitah">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/head.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Vitah's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Pomelo教程(10)-建筑升级倒计时的处理
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-10T11:40:33+08:00">
                2017-04-10
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Pomelo/" itemprop="url" rel="index">
                    <span itemprop="name">Pomelo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/posts/bc618efe/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="posts/bc618efe/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><strong>系统版本：macOS 10.12.3，Pomelo版本：1.2.3，Unity版本：5.4.4f1</strong></p>
<p><strong>Pomelo Demo 服务端代码：<a href="https://github.com/vitahlin/VitahPomeloServer" target="_blank" rel="external">https://github.com/vitahlin/VitahPomeloServer</a></strong></p>
<p><strong>Pomelo Demo 客户端代码：<a href="https://github.com/vitahlin/VitahPomeloClient" target="_blank" rel="external">https://github.com/vitahlin/VitahPomeloClient</a></strong></p>
<p>除了基本的信息交互，我们在游戏中也会时常遇到有倒计时的功能。比如说，建筑的升级需要倒计时，技能的升级需要倒计时，装备的建造等等。</p>
<p>这里，我们以建筑升级为例来说明类似功能的实现。一般服务端只记录升级的结束时间，倒计时放在客户端来实现，当客户端倒计时结束的时候，通知服务端刷新。服务端每次取相关表的时候也对排程进行刷新。</p>
<a id="more"></a>
<h3 id="创建保存建筑数据的-schema-和-model"><a href="#创建保存建筑数据的-schema-和-model" class="headerlink" title="创建保存建筑数据的 schema 和 model"></a>创建保存建筑数据的 schema 和 model</h3><h4 id="保存单个建筑信息"><a href="#保存单个建筑信息" class="headerlink" title="保存单个建筑信息"></a>保存单个建筑信息</h4><p>我们创建 <code>game-server/app/schemas/build/buildItemSchema.js</code> 用来保存单个建筑的信息：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">buildItemschema.methods.isUpgradeTimeUp = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</div><div class="line">	<span class="keyword">if</span> (moment() &gt;= moment(<span class="keyword">this</span>.up_end_time) &amp;&amp; moment(<span class="keyword">this</span>.up_end_time).unix() != moment(<span class="number">0</span>).unix()) &#123;</div><div class="line">		<span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	<span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">&#125;;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * [isEndUpgrade 判断是否升级完成（加上5秒的误差时间）]</div><div class="line"> * @return &#123;Boolean&#125; [description]</div><div class="line"> */</div><div class="line">buildItemschema.methods.isEndUpgrade = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</div><div class="line">	<span class="keyword">if</span> (moment().add(<span class="number">5</span>, <span class="string">'s'</span>) &gt;= moment(<span class="keyword">this</span>.up_end_time) &amp;&amp; moment(<span class="keyword">this</span>.up_end_time).unix() != moment(<span class="number">0</span>).unix()) &#123;</div><div class="line">		<span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	<span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">&#125;;</div></pre></td></tr></table></figure></p>
<p>注意代码中的这两个函数，<code>isUpgradeTimeUp</code>用于在服务端进行判断倒计时是否结束，而<code>isEndUpgrade</code>则是客户端倒计时结束后，通知服务端这个建筑已经升级完成了，应该对它的等级进行升级，这时候服务端进行验证的时候加入少许的误差时间。</p>
<h4 id="保存用户的全部信息"><a href="#保存用户的全部信息" class="headerlink" title="保存用户的全部信息"></a>保存用户的全部信息</h4><p>然后创建 <code>game-server/app/schemas/buildSchema.js</code> 用来保存用户的全部建筑信息：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> buildSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</div><div class="line">	<span class="comment">// 用户id</span></div><div class="line">	uid: &#123;</div><div class="line">		<span class="attr">type</span>: <span class="built_in">Number</span>,</div><div class="line">		<span class="attr">required</span>: <span class="literal">true</span>,</div><div class="line">		<span class="attr">unique</span>: <span class="literal">true</span>,</div><div class="line">		<span class="attr">index</span>: <span class="literal">true</span></div><div class="line">	&#125;,</div><div class="line"></div><div class="line">	<span class="comment">// 建筑列表</span></div><div class="line">	build_list: [buildItemSchema],</div><div class="line"></div><div class="line">	<span class="attr">build_max_id</span>: &#123;</div><div class="line">		<span class="attr">type</span>: <span class="built_in">Number</span>,</div><div class="line">		<span class="attr">default</span>: <span class="number">10000</span></div><div class="line">	&#125;</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * 建筑自增id</div><div class="line"> * @return &#123;[type]&#125; [description]</div><div class="line"> */</div><div class="line">buildingSchema.methods.genBuildId = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</div><div class="line">	<span class="keyword">this</span>.build_max_id++;</div><div class="line">	<span class="keyword">return</span> <span class="keyword">this</span>.build_max_id;</div><div class="line">&#125;;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * 添加建筑</div><div class="line"> * @param &#123;[type]&#125; build_type [要添加的建筑类型]</div><div class="line"> * @param &#123;[type]&#125; position   [建筑位置]</div><div class="line"> * @param &#123;[type]&#125; rotation   [建筑旋转角度]</div><div class="line"> */</div><div class="line">buildingSchema.methods.addBuild = <span class="function"><span class="keyword">function</span>(<span class="params">build_type</span>) </span>&#123;</div><div class="line">	<span class="keyword">var</span> new_build_id = <span class="keyword">this</span>.genBuildId();</div><div class="line">	<span class="keyword">this</span>.build_list.push(&#123;</div><div class="line">		<span class="attr">build_id</span>: new_build_id,</div><div class="line">		<span class="attr">lv</span>: <span class="number">0</span>,</div><div class="line">		<span class="attr">type</span>: build_type</div><div class="line">	&#125;);</div><div class="line"></div><div class="line">	<span class="keyword">return</span> new_build_id;</div><div class="line">&#125;;</div></pre></td></tr></table></figure></p>
<p>注意其中的 <code>build_list</code> 是一个列表，保存所有建筑。<code>build_max_id</code> 则是用于生成每个建筑独一无二的建筑 ID。</p>
<h4 id="在-buildModel-js-中对排程进行刷新"><a href="#在-buildModel-js-中对排程进行刷新" class="headerlink" title="在 buildModel.js 中对排程进行刷新"></a>在 buildModel.js 中对排程进行刷新</h4><p>然后我们在每次取相关表的时候需要对排程进行刷新<br><code>game-server/app/model/buildModel.js</code>：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">module</span>.exports.getByUid = <span class="function"><span class="keyword">function</span>(<span class="params">uid, cb</span>) </span>&#123;</div><div class="line">	modelUtil.getByUid(Build, uid, <span class="function"><span class="keyword">function</span>(<span class="params">err, build_model</span>) </span>&#123;</div><div class="line">		<span class="keyword">if</span> (!!err) &#123;</div><div class="line">			<span class="built_in">console</span>.error(err);</div><div class="line">			<span class="keyword">return</span> cb(err);</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		dealSchedule(build_model, <span class="function"><span class="keyword">function</span>(<span class="params">err</span>) </span>&#123;</div><div class="line">			<span class="keyword">if</span> (build_model.isModified()) &#123;</div><div class="line">				build_model.save(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</div><div class="line">					cb(<span class="literal">null</span>, build_model);</div><div class="line">				&#125;);</div><div class="line">			&#125; <span class="keyword">else</span> &#123;</div><div class="line">				cb(<span class="literal">null</span>, build_model);</div><div class="line">			&#125;</div><div class="line">		&#125;);</div><div class="line">	&#125;);</div><div class="line">&#125;;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * 处理建筑中的排程</div><div class="line"> * @param  &#123;[type]&#125;   build_model [description]</div><div class="line"> * @param  &#123;Function&#125; cb          [description]</div><div class="line"> * @return &#123;[type]&#125;               [description]</div><div class="line"> */</div><div class="line"><span class="keyword">var</span> dealSchedule = <span class="function"><span class="keyword">function</span>(<span class="params">build_model, cb</span>) </span>&#123;</div><div class="line">	<span class="keyword">var</span> build_change = <span class="literal">false</span>;</div><div class="line">	<span class="keyword">var</span> build_old_json = build_model.toJSON();</div><div class="line">	_.each(build_model.getBuildList(), <span class="function"><span class="keyword">function</span>(<span class="params">build_item</span>) </span>&#123;</div><div class="line">		<span class="keyword">if</span> (build_item.isUpgradeTimeUp()) &#123;</div><div class="line">			build_change = <span class="literal">true</span>;</div><div class="line">			build_item.upgrade();</div><div class="line">		&#125;</div><div class="line">	&#125;);</div><div class="line"></div><div class="line">	<span class="keyword">var</span> uid = build_model.uid;</div><div class="line">	<span class="keyword">if</span> (build_change) &#123;</div><div class="line">			pushService.pushBuildModify(uid, build_old_json, build_model.toJSON());</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	cb();</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>注意上文中的代码：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (build_item.isUpgradeTimeUp()) &#123;</div><div class="line">    build_change = <span class="literal">true</span>;</div><div class="line">    build_item.upgrade();</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>在每次取用户表的时候，取完都会对建筑列表进行遍历，如果其中有倒计时时间结束的，则升级该建筑。并且这个判断时间是否结束，不加入对误差的处理，因为这是在服务端自身进行判断的，客户端并没有对此进行倒计时。</p>
<h3 id="实现升级和刷新相关协议"><a href="#实现升级和刷新相关协议" class="headerlink" title="实现升级和刷新相关协议"></a>实现升级和刷新相关协议</h3><h4 id="升级协议"><a href="#升级协议" class="headerlink" title="升级协议"></a>升级协议</h4><p>升级协议<code>game-server/app/servers/build/handler/build/upgrade.js</code><br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> build_item = build_model.getBuild(build_id);</div><div class="line"><span class="keyword">if</span> (!build_item) &#123;</div><div class="line">	<span class="keyword">return</span> next(<span class="literal">null</span>, &#123;</div><div class="line">		<span class="attr">code</span>: code.BUILD_NOT_EXIST</div><div class="line">	&#125;);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 判断建筑是否在升级</span></div><div class="line"><span class="keyword">if</span> (build_item.getUpRemainTime() &gt; <span class="number">0</span>) &#123;</div><div class="line">	<span class="keyword">return</span> next(<span class="literal">null</span>, &#123;</div><div class="line">		<span class="attr">code</span>: code.BUILD_IS_IN_UPGRADE</div><div class="line">	&#125;);</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">	<span class="comment">// 建筑不在升级中，并且升级结束时间不为0，表示当前建筑上次升级以及完成，升级该建筑</span></div><div class="line">	<span class="keyword">if</span> (moment(build_item.up_end_time).unix() != moment(<span class="number">0</span>).unix())&#123;</div><div class="line">		build_item.upgrade();</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 设置建筑升级结束时间</span></div><div class="line">build_item.setUpEndTime(<span class="number">300</span>);</div></pre></td></tr></table></figure></p>
<p>升级时会优先判断该建筑是否存在，所以在建筑升级前，我们应该建造该建筑，可以新建建造协议来完成此功能。然后升级时，判断该建筑是否在升级中，是的话返回错误码，不是的话直接设置升级结束时间，数据下发给客户端，由客户端开始倒计时功能。</p>
<h4 id="建造协议"><a href="#建造协议" class="headerlink" title="建造协议"></a>建造协议</h4><p>建造协议<code>game-server/app/servers/build/handler/buildHandler.js</code>：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> new_build_id = build_model.addBuild(build_type);</div><div class="line"><span class="keyword">var</span> build = build_model.getBuild(new_build_id);</div><div class="line">build.setUpEndTime(<span class="number">300</span>);</div></pre></td></tr></table></figure></p>
<p>注意这三行代码，其实也就是把建造这个过程看作是建筑从0级到1级的升级过程，可以到<code>BuildSchema.js</code>中参考函数的具体代码。</p>
<h4 id="倒计时刷新协议"><a href="#倒计时刷新协议" class="headerlink" title="倒计时刷新协议"></a>倒计时刷新协议</h4><p>倒计时结束刷新协议<code>game-server/app/servers/build/handler/build/refresh.js</code><br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span> (<span class="params">msg, session, next</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> uid = session.uid;</div><div class="line">    <span class="keyword">var</span> build_id = msg.build_id;</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (!uid || !build_id) &#123;</div><div class="line">        <span class="keyword">return</span> next(<span class="literal">null</span>, &#123;</div><div class="line">            <span class="attr">code</span>: code.PARAM_ERROR</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">var</span> onRefresh = <span class="function"><span class="keyword">function</span>* (<span class="params"></span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> model_change = <span class="literal">false</span>;</div><div class="line">        <span class="keyword">var</span> build_model = <span class="keyword">yield</span> thunkify(buildModel.getByUid)(uid);</div><div class="line">        <span class="keyword">var</span> build_old_json = build_model.toJSON();</div><div class="line"></div><div class="line">        <span class="keyword">var</span> refresh_build = &#123;&#125;;</div><div class="line">        _.each(build_model.getBuildList(), <span class="function"><span class="keyword">function</span> (<span class="params">build_item</span>) </span>&#123;</div><div class="line">            <span class="keyword">if</span> (build_item.build_id == build_id) &#123;</div><div class="line">                <span class="keyword">if</span> (build_item.isEndUpgrade()) &#123;</div><div class="line">                    model_change = <span class="literal">true</span>;</div><div class="line">                    build_item.upgrade();</div><div class="line">                    refresh_build = build_item.toJSON();</div><div class="line">                &#125;</div><div class="line">            &#125; <span class="keyword">else</span> &#123;</div><div class="line">                <span class="keyword">if</span> (build_item.isUpgradeTimeUp()) &#123;</div><div class="line">                    model_change = <span class="literal">true</span>;</div><div class="line">                    build_item.upgrade();</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">        &#125;);</div><div class="line"></div><div class="line">        <span class="keyword">yield</span> build_model.save();</div><div class="line"></div><div class="line">        <span class="keyword">if</span> (model_change) &#123;</div><div class="line">            pushService.pushBuildModify(uid, build_old_json, build_model.toJSON());</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">return</span> next(<span class="literal">null</span>, &#123;</div><div class="line">            <span class="attr">code</span>: code.OK,</div><div class="line">            <span class="attr">result</span>: &#123;</div><div class="line">                <span class="attr">build_info</span>: refresh_build</div><div class="line">            &#125;</div><div class="line">        &#125;);</div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    <span class="keyword">var</span> onError = <span class="function"><span class="keyword">function</span> (<span class="params">err</span>) </span>&#123;</div><div class="line">        <span class="built_in">console</span>.error(err);</div><div class="line">        <span class="keyword">return</span> next(<span class="literal">null</span>, &#123;</div><div class="line">            <span class="attr">code</span>: code.FAIL</div><div class="line">        &#125;);</div><div class="line">    &#125;;</div><div class="line">    co(onRefresh).catch(onError);</div><div class="line">&#125;;</div></pre></td></tr></table></figure></p>
<p>倒计时放在客户端计算，在界面打开时应该一直处于倒计时状态，倒计时结束后，调用该协议将客户端认为升级结束的建筑 ID 发给服务端，服务端进行验证（验证的时候为了准确性应该允许些许时间误差），验证后成功，将该建筑升级，把新的建筑数据推送下去。</p>
<p>这样我们就完成了含有倒计时的整个的建筑的功能。类似技能的升级、技能点研发、装备的建造等等都可以按类似的套路来完成。可以在客户端中跳转到建筑界面进行功能的测试。</p>

      
    </div>
    
    <div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="http://jslibs.wuxubj.cn/sweetalert_mini/jquery-1.7.1.min.js"></script>
  <script src="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.mini.css">

  <p><span>本文标题:</span><a href="/posts/bc618efe/">Pomelo教程(10)-建筑升级倒计时的处理</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Vitah 的个人博客">Vitah</a></p>
  <p><span>发布时间:</span>2017年04月10日 - 11:04</p>
  <p><span>最后更新:</span>2017年04月10日 - 11:04</p>
  <p><span>原始链接:</span><a href="/posts/bc618efe/" title="Pomelo教程(10)-建筑升级倒计时的处理">http://www.vitah.net/posts/bc618efe/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://www.vitah.net/posts/bc618efe/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>

<script> 
    var clipboard = new Clipboard('.fa-clipboard');
	clipboard.on('success', $(function(){
	  $(".fa-clipboard").click(function(){
		swal({   
		  title: "",   
		  text: '复制成功',   
		  html: false,
		  timer: 500,   
		  showConfirmButton: false
	    });
	  });
    }));  
</script>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div></div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/images/wechatpay.jpeg" alt="Vitah WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/images/alipay.jpeg" alt="Vitah Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Node-js/" rel="tag"># Node.js</a>
          
            <a href="/tags/Pomelo/" rel="tag"># Pomelo</a>
          
            <a href="/tags/Unity3D/" rel="tag"># Unity3D</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/3c449ea0/" rel="next" title="shell传入参数处理的简单介绍">
                <i class="fa fa-chevron-left"></i> shell传入参数处理的简单介绍
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/5adaeec5/" rel="prev" title="Pomelo教程(11)-定时任务之cron">
                Pomelo教程(11)-定时任务之cron <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/head.JPG"
               alt="Vitah" />
          <p class="site-author-name" itemprop="name">Vitah</p>
           
              <p class="site-description motion-element" itemprop="description">深自缄默，如云漂泊。</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">47</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/vitahlin" target="_blank" title="Github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  Github
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:linw1225@163.com" target="_blank" title="Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                  Mail
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-block">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://shuge.org/" title="书格" target="_blank">书格</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://taozj.org/" title="taozj" target="_blank">taozj</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://oserror.com/" title="Charles" target="_blank">Charles</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.hsmouc.com/" title="Hsmouc" target="_blank">Hsmouc</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建保存建筑数据的-schema-和-model"><span class="nav-number">1.</span> <span class="nav-text">创建保存建筑数据的 schema 和 model</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#保存单个建筑信息"><span class="nav-number">1.1.</span> <span class="nav-text">保存单个建筑信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#保存用户的全部信息"><span class="nav-number">1.2.</span> <span class="nav-text">保存用户的全部信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在-buildModel-js-中对排程进行刷新"><span class="nav-number">1.3.</span> <span class="nav-text">在 buildModel.js 中对排程进行刷新</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实现升级和刷新相关协议"><span class="nav-number">2.</span> <span class="nav-text">实现升级和刷新相关协议</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#升级协议"><span class="nav-number">2.1.</span> <span class="nav-text">升级协议</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#建造协议"><span class="nav-number">2.2.</span> <span class="nav-text">建造协议</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#倒计时刷新协议"><span class="nav-number">2.3.</span> <span class="nav-text">倒计时刷新协议</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Vitah</span>
</div>



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      访客
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  








  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://http-www-vitah-net.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://www.vitah.net/posts/bc618efe/';
          this.page.identifier = 'posts/bc618efe/';
          this.page.title = 'Pomelo教程(10)-建筑升级倒计时的处理';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://http-www-vitah-net.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>





  

  

  

  

  

</body>
</html>
